<template>
    <div class="app-container">
        <el-form :model="user" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
            <el-form-item label="用户账号" prop="account" disabled>
                <el-input v-model="user.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pwd" >
                <el-input v-model="user.pwd" type="password"></el-input>
            </el-form-item>
            <el-form-item class="myuploader" label="用户头像" prop="img" >
                <el-upload
                ref="uploader"
                class="upload-demo"
                :on-change="handleChange"
                :action="uploadUrl"
                :file-list="fileList"
                :data="user"
                :multiple="false"
                :http-request="uploadSectionFile"
                :auto-upload="false"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="昵称" prop="realName" >
                <el-input v-model="user.realName"></el-input>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="user.birthday" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone" >
                <el-input v-model="user.phone"></el-input>
            </el-form-item>
            <el-form-item label="用户类型" prop="userType">
              <el-radio-group v-model="user.userType" disabled>
                <el-radio-button :label="1">系统管理员</el-radio-button>
                <el-radio-button :label="2">普通用户</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="注册类型" prop="phone" >
              <el-radio-group v-model="user.regType" disabled>
                <el-radio-button :label="1">账户注册</el-radio-button>
                <el-radio-button :label="2">手机注册</el-radio-button>
                <el-radio-button :label="3">微信注册</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="微信号" prop="phone" >
                <el-input v-model="user.wxAccount"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
                <el-button @click="returnPage()">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
    
</template>

<script>
  import { updateUserApi } from '@/api/user'
  import { getUserApi } from '@/api/user'
  export default {
    data() {
      return {
        changeUserImg: false,
        imgPath:process.env.VUE_APP_BASE_API,
        fileList:[],
        uploadUrl:process.env.VUE_APP_BASE_API+'/user',
        user: {
        },
        rules: {
          account: [
            { required: true, message: '请输入用户账号', trigger: 'blur' }
          ],
          pwd: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入昵称', trigger: 'blur' }
          ],
          phone: [
            { message: '请输入手机号码',trigger: 'blur'},
	    	      {validator:function(rule,value,callback){
	            if(/^1[34578]\d{9}$/.test(value) == false){
	                callback(new Error("请输入正确的手机号"));
	            }else{
	                callback();
	            }
            }, trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.user.id = this.$route.params.id
      this.getUser(this.user.id)
    },
    methods: {
      getUser(id) {
        getUserApi(id)
          .then(response=>{
            this.user = response.data
            this.fileList=[{url:this.imgPath + this.user.img, status: "ready"}]
            delete this.user.createTime
          })
      },
      uploadSectionFile(params) {
          const file = params.file,
            fileType = file.type,
            isImage = fileType.indexOf("image") != -1,
            isLt2M = file.size / 1024 / 1024 < 2
          // 这里常规检验，看项目需求而定
          if (!isImage) {
            this.$message.error("只能上传图片格式png、jpg、jpeg、gif!")
            return
          }
          if (!isLt2M) {
            this.$message.error("只能上传图片大小小于2M")
            return
          }
          // 根据后台需求数据格式
          const form = new FormData()
          // 文件对象
          form.append("file", file)
          //遍历user转formdata格式键值对
          delete this.user.userImg
          Object.keys(this.user).forEach((key) => {
           form.append(key, this.user[key])
          })
          this.updateUser(form);
      },
      updateUser(form) {
        updateUserApi(form)
            .then(res => {
              if(res.status == 0){
                this.$message('提交成功')
              }
              this.$router.push('/relation/user')
            })
      },
      handleChange(file, fileList) {
        console.log(file);
        const isPNG = file.raw.type === "image/png"
        const isJPG = file.raw.type === "image/jpg"
        const isJPEG = file.raw.type === "image/jpeg"
        const isGIF = file.raw.type === "image/gif"
        const isLt2M = file.raw.size / 1024 / 1024 < 0.5
        if (fileList.length > 0) {
        //单个覆盖上传
          this.fileList = [fileList[fileList.length - 1]] // 这一步，是 展示最后一次选择的csv文件
          if (!isPNG && !isJPG && !isJPEG && !isGIF) {
            this.$message.error("只能上传图片格式png、jpg、jpeg、gif!")
            this.fileList = []
            return false
          } else if (!isLt2M) {
            this.$message.error("上传图片大小不能超过 200kb!")
            this.fileList = []
            return false
          }
          this.changeUserImg = true
          return true
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.changeUserImg){
              this.$refs.uploader.submit()
            }else{
              var formData = new FormData()
              Object.keys(this.user).forEach((key) => {
               formData.append(key, this.user[key])
              }) 
              this.updateUser(formData)
            }
          } 
        })
      },
      returnPage() {
        if (window.history.length <= 1) {
          this.$router.push({ path: "/zh-CN/home" });
          return false;
        } else {
          this.$router.go(-1);
        }
      }
    }
  }
</script>

<style scoped>
    .myuploader >>> .el-list-enter-active,.myuploader >>> .el-list-leave-active{
        transition: none;
    }

    .myuploader >>>.el-list-enter,.myuploader >>> .el-list-leave-active {
      opacity: 0;
    }
</style>